package com.fsp.blog.handle;

import com.alibaba.fastjson.JSON;
import com.fsp.blog.pojo.SysUser;
import com.fsp.blog.service.LoginService;
import com.fsp.blog.utils.UserThreadLocal;
import com.fsp.blog.vo.ErrorCode;
import com.fsp.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author fushengping
 * @className LoginInterceptor
 * @description 拦截器
 * @date 2021/11/14 23:36
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
        * 再执行controller(handler)方法前执行
        * 1.判断该请求接口路径是不是HandlerMethod(controller方法)
        * 2.判断token是否为空，为空则未登录
        * 3.token不为空，进行登录认证
        * 4.认证成功进行放行
        * */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取请求头的token
        String token = request.getHeader("Authorization");
        log.info("==============request start============");
        String requestURI = request.getRequestURI();
        log.info("requestURI uri{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}",token);
        log.info("==============request end============");
        if (StringUtils.isBlank(token)) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //进行token验证
        SysUser sysUser = loginService.checkToken(token);
        if (sysUser == null) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //是登录状态，放行
        //希望在controller中直接获取用户信息(使用本地ThreadLocal)
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove(); //删除信息，否则容易造成内存泄露
    }
}
